package store

import (
	"time"

	"github.com/sirupsen/logrus"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type orm struct {
	*gorm.DB // mysql db instance
}

// New Store, dsn for mysql
func New(dsn string, debug bool) Store {
	logLevel := logger.Warn
	if debug {
		logLevel = logger.Info
	}
	db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logLevel),
	})
	if err != nil {
		logrus.Fatal("database open: ", err)
	}
	if sqlDB, err := db.DB(); err != nil {
		logrus.Fatal("database open: ", err)
	} else {
		sqlDB.SetConnMaxLifetime(time.Second * 3600)
	}
	return &orm{
		DB: db,
	}
}

func (o *orm) GetTransaction() *gorm.DB {
	return o.Begin()
}
